package dao.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import utils.Utils;
import webserver.Consts;
import dao.ILoader;
import dao.models.Answer;
import dao.models.Chapter;
import dao.models.Question;

public class StringLoader implements ILoader {

    private static final String QUESTIONS = "@@Question\\n*([^@]*)@@Answers\\n*([^@]*)";
    private static final String CHAPTERS = "@@Chapter\\n*[^@]*\\n*\\@@Name\\n*([^@]*)\\n*@@Text\\n*([^@]*)@@Questions\\n*[^@]*(("
	    + QUESTIONS + ")+)";
    private static Pattern all = Pattern.compile(StringLoader.CHAPTERS);
    private static Pattern question = Pattern.compile(StringLoader.QUESTIONS);

    public List<Chapter> getChapters() {
	String str = Utils.deserializeString(new File(
		Consts.PATH_TO_QUESTIONS));
	Matcher parsedText = all.matcher(str);
	List<Chapter> res = new ArrayList<Chapter>();
	int chapterIds = 0;
	int questionIds = 0;
	int answerIds = 0;
	while (parsedText.find()) {
	    Chapter c = new Chapter();
	    c.setId(chapterIds++);
	    c.setName(parsedText.group(1).trim());
	    c.setText(parsedText.group(2).trim());
	    String questions = parsedText.group(3);
	    Matcher questionsMatcher = question.matcher(questions);
	    List<Question> questionList = new ArrayList<Question>();
	    while (questionsMatcher.find()) {
		Question q = new Question();
		q.setId(questionIds++);
		q.setText(questionsMatcher.group(1).trim());
		String answers = questionsMatcher.group(2).trim();
		List<String> rawList = Arrays.asList(answers.split("\n"));
		List<Answer> finalList = new ArrayList<Answer>();
		for (String string : rawList) {
		    Answer answer = new Answer();
		    answer.setId(answerIds++);
		    answer.setAnswer(string.trim());
		    finalList.add(answer);
		}
		q.setAnswers(finalList);
		questionList.add(q);
	    }
	    c.setQuestions(questionList);
	    res.add(c);
	}
	return res;
    }

    @Override
    public Chapter getChapter(String id) {
	return getChapters().get(Integer.parseInt(id));
    }

    @Override
    public Answer getAnswerById(String answerId) {
	int id = Integer.parseInt(answerId);
	for (Chapter chapter : getChapters()) {
	    for (Question question : chapter.getQuestions()) {
		for (Answer answer : question.getAnswers()) {
		    if (answer.getId() == id) {
			return answer;
		    }
		}
	    }
	}
	throw new Error("Couldn't find answer with id " + id);
    }
}
